#!/usr/bin/env python
# coding: utf-8


import os
import time
import subprocess
from UiManager.models import DeviceInfo, TestSuiteInfo, SystemSettings
from Alpaca.settings import NODE_PATH, MAIN_JS_PATH, SETTINGS,  UIAUTOMATOR

system_opt = SystemSettings.objects.get(id=1)


def check_conf(suite_name, time_volue):
    """
    循环查找是否有在执行case的Android设备，有可用的设备标记isused状态为true
    :return:
    """
    device_info = {}
    for i in range(time_volue):
        # 获取全部设备
        device_opt = DeviceInfo.objects.all()
        for obj in device_opt:
            if obj.isused == "False":
                device_info['deviceid'] = obj.deviceid
                device_info['port'] = obj.port
                device_info['bport'] = obj.bport
                device_info['aport'] = obj.aport

                # 修改设备状态
                obj.isused = "True"
                obj.tag = suite_name
                obj.save()
                print('找到可运行设备')
                return {'status': '0', 'message': 'success', 'content': device_info}
        print('没有可运行设备，等待60s')
        time.sleep(60)
    return {'status': '-1', 'message': 'failed'}


def resetDevice(deviceid=None, suite_id=None, duration=None):
    """
    重置设备和suite状态
    :return:
    """
    # 获取全部设备
    try:
        if deviceid:
            device_obj = DeviceInfo.objects.get(deviceid=deviceid)
            device_obj.isused = "False"
            device_obj.tag = ''
            device_obj.save()
        if suite_id:
            suite_obj = TestSuiteInfo.objects.get(id=suite_id)
            suite_obj.status = "False"
            suite_obj.duration = duration
            suite_obj.save()
    except:
        return '设备状态重置失败'


def startServer(device_info):
    """
    通过端口号杀掉对应端口的appium服务，再启动对应端口的appium server
    :return:
    """
    nowtime = time.strftime('%Y%m%d%H%M%S')
    port = device_info['port']
    bport = device_info['bport']
    deviceid = device_info['deviceid']

    # 通过端口号杀掉appiumserver
    killAppiumServer = "lsof -i:%s | grep node | awk '{print $2}' | xargs kill -9 " % port
    print('杀死appium命令为：%s' % killAppiumServer)
    os.system(killAppiumServer)
    time.sleep(3)

    # 启动appium服务
    log = SystemSettings.objects.get(id=1).log_dir
    start_appium_cmd = ' '.join([NODE_PATH, system_opt.main_dir, SETTINGS])
    start_appium_cmd = start_appium_cmd + '  -U "%s" -p "%s" -bp "%s"> %s.log' % (
    deviceid, port, bport, log + '/' +deviceid + "_" + nowtime)
    print('启动appium命令： %s' % start_appium_cmd)
    execcommand2(start_appium_cmd)


def jurisdiction(deviceid, package, app_path):
    """
    :param deviceid:  设备id
    :param package:  apk包名
    :return: None
    """
    try:
        os.system("adb -s " + deviceid + " uninstall " + package)
        os.system("adb -s " + deviceid + " shell am force-stop com.huawei.systemmanager")
        os.system("adb -s " + deviceid + " install " + app_path)
        os.system("adb -s " + deviceid + " shell uiautomator runtest Test.jar -c com.uiautomator.test.%s" % UIAUTOMATOR.get(package, None))
        return 'success'
    except:
        return '处理app权限失败, 请检查环境中包名是否正确或者检查Test.jar权限类中是否有关于此包的处理。'


def screen(driver):
    now = time.strftime('%Y%m%d %H%M%S')
    # pic_path = system_opt.image_dir + '/' + now + '.png'
    pic_path = os.getcwd() + system_opt.image_dir  + '/' + now + '.png'
    driver.save_screenshot(pic_path)
    return system_opt.image_dir + '/' + now + '.png'


def start_anyproxy(device_info, rule=None):
    """
    启动anyproxy代理服务
    :param rule: 
    :return: none
    """
    # 获取设备预先绑定启动端口号
    proxy_port = device_info['aport']
    web_gui_port = int(proxy_port) + 1

    """
    anyproxy 命令详解
    Options:
    -V, --version              output the version number
    -p, --port [value]         proxy port, 8001 for default
    -w, --web [value]          web GUI port, 8002 for default
    -r, --rule [value]         path for rule file,
    -l, --throttle [value]     throttle speed in kb/s (kbyte / sec)
    -i, --intercept            intercept(decrypt) https requests when root CA exists
    -s, --silent               do not print anything into terminal
    -c, --clear                clear all the certificates and temp files
    --ws-intercept             intercept websocket
    --ignore-unauthorized-ssl  ignore all ssl error
    -h, --help                 output usage information
    """
    # 启动服务命令拼装
    # 获取rule文件绝对路径
    system_opt = SystemSettings.objects.get(id=1)
    if rule:
        rule = os.path.join(system_opt.resource_dir, rule)
        start_cmd = 'anyproxy -i -p %s -w %s -r %s' % (str(proxy_port), str(web_gui_port), rule)
    else:
        start_cmd = 'anyproxy -i -p %s -w %s' % (str(proxy_port), str(web_gui_port))
    execcommand2(start_cmd)
    print('启动anyproxy命令：%s' % start_cmd)


def kill_anyproxy(proxy_port):
    # 杀死anyproxy服务
    kill_cmd = "lsof -i:%s | grep %s | awk -F' ' '{print $2}' | xargs kill -9" % (str(proxy_port), str(proxy_port))
    execcommand2(kill_cmd)
    

def execcommand(command):
    p = os.popen(command).read()
    commandRes = p.strip()
    time.sleep(5)
    if commandRes:
        return commandRes
    else:
        return ""


def execcommand2(comand):
    # 以shell方式执行命令，用来执行anyproxy命令
    subprocess.Popen(comand, shell=True)
    time.sleep(10)


def execcommand3(command):
    os.system(command)


if __name__ == '__main__':
    print(execcommand2('anyproxy -i -p 8003 -w 8004'))